﻿@using System.IO;
@using System.IO.Ports;
@using System.Text.Json;
@using System.Diagnostics;

<BootstrapBlazorRoot>

<div class="row">
    <div class="col-9">
        <C485SrvCmd @ref="srv_cmd"></C485SrvCmd>
        <Divider />
        <C485Log @ref="log"></C485Log>

        <div class="row">
            <div class="col-2"> <h5>选择连接智能模块串口：</h5> </div>
            <div class="col-2"><Select Color="Color.Warning" Items="pc_comm_list" @bind-Value="com_port"></Select></div>
            <div class="col-2">
                <button class="btn btn-primary" @onclick="btn_start_click"> <i class="fas fa-play"> </i> @btn_start_txt </button>
            </div>
        </div>
    </div>


    <div class="col-3">
        <C485ParamTb @ref="param_tb"></C485ParamTb>
    </div>
</div>



</BootstrapBlazorRoot>

@code {
    private C485Log log;
    private C485Uart uart = new C485Uart();
    private C485SrvCmd srv_cmd;
    private C485ParamTb param_tb;

    private string btn_start_txt = "启动控制器";
    private Process? ctrl_process = null;
    private System.Timers.Timer task_timer = new(50);  // 50ms loop

    private byte[] rx_buf = new byte[4096];
    private int rx_cnt = 0;

    private void OnTimedEvent(object source, System.Timers.ElapsedEventArgs e)
    {

        // try recv uart data
        byte[]? data = null;
        int recv_len = uart.Recv(rx_buf, rx_cnt, rx_buf.Length - rx_cnt);
        rx_cnt += recv_len;
        int cur_len = rx_cnt;
        if (rx_cnt > 0)
        {
            if (rx_cnt > 64) rx_cnt = 65; // 超长截断
            if (rx_cnt >= 14)
            {
                data = new byte[rx_cnt];
                Array.Copy(rx_buf, data, rx_cnt);
                rx_cnt = 0;
            }
            else if (rx_buf[0] != 0xDD) // 硬件上电会有一些干扰数据，所以如果收到不是DD开头的，干脆清除
            {
                rx_cnt = 0;
            }
        }
        _ = InvokeAsync(() =>
        {
            if (recv_len > 0)
                log.AddItem(rx_buf, cur_len, 0);
            srv_cmd.Update(data);
            param_tb.Update();
        });
    }

    private void btn_start_click()
    {
        if (btn_start_txt == "启动控制器")
        {
            btn_start_txt = "关闭控制器";
            // 打开串口
            uart.Open(com_port, log);
            srv_cmd.uart = uart;
            // 启动定时器
            task_timer.Elapsed += OnTimedEvent;
            task_timer.Start();
            // 初始化子组件
            srv_cmd.param_tb = param_tb;

            // 启动控制器模拟器
            // ProcessStartInfo startInfo = new ProcessStartInfo("..\\..\\..\\..\\zy_simu\\bin\\debug\\net8.0-windows10.0.19041.0\\zy_simu.exe");
            // startInfo.UseShellExecute = false;
            // startInfo.CreateNoWindow = false; // 开启自己的控制台来输出log
            // ctrl_process = Process.Start(startInfo);
        }
        else
        {
            btn_start_txt = "启动控制器";
            uart.Close();
            task_timer.Stop();
            srv_cmd.uart = null;
            // if (ctrl_process != null)
            // {
            //     ctrl_process.Kill();
            //     ctrl_process.Close();
            //     ctrl_process = null;
            // }
        }
    }

    private IEnumerable<SelectedItem> pc_comm_list { get; set; } = new[] { new SelectedItem("", "") };
    private string com_port = "";
    protected override void OnInitialized()
    {
        // 收集系统中的串口供选择
        string[] names = SerialPort.GetPortNames();
        List<SelectedItem> comm = new();
        foreach (string s in names)
        {
            comm.Add(new SelectedItem(s, s));
        }
        pc_comm_list = comm;
        base.OnInitialized();
    }

}